package misc

import (
	"encoding/base64"

	"gitee.com/ameise84/e3utils/bytes_buffer"
	jsoniter "github.com/json-iterator/go"
	"servers/crypto"

	"servers/models/meta"
)

var gBytesPool bytes_buffer.Pool[bytes_buffer.ShiftBuffer]

func init() {
	gBytesPool = bytes_buffer.NewShiftBufferPool(1024, 0, true)
}

func ParseGameUrlToken(cipher crypto.Cipher, urlParams *meta.GameURLParams) (string, error) {
	encryptStr, err := jsoniter.Marshal(urlParams)
	if err != nil {
		return "", err
	}

	buf := gBytesPool.Get()
	defer gBytesPool.Put(buf)
	needCap := len(encryptStr) + 64
	if buf.GetCapacity() < needCap {
		_ = buf.Reserve(needCap)
	}
	encryptToken, _ := buf.GetTailEmptyBytes()

	if encryptToken, err = cipher.Encrypt(encryptStr, encryptToken); err != nil {
		return "", err
	}
	return base64.URLEncoding.EncodeToString(encryptToken), nil
}

func UnparseGameUrlToken(cipher crypto.Cipher, token string, urlParams *meta.GameURLParams) error {
	bs, err := base64.URLEncoding.DecodeString(token)
	if err != nil {
		return err
	}

	buf := gBytesPool.Get()
	defer gBytesPool.Put(buf)
	needCap := len(token)
	if buf.GetCapacity() < needCap {
		_ = buf.Reserve(needCap)
	}
	buf.Clean()
	decryptToken, _ := buf.GetTailEmptyBytes()
	if decryptToken, err = cipher.Decrypt(bs, decryptToken); err != nil {
		return err
	}
	return jsoniter.Unmarshal(decryptToken, urlParams)
}
